
let _Vue = null
export default class VueRouter {
    static install(Vue){
        //判断当前插件是否已经被安装
        if(VueRouter.install.installed) return
        VueRouter.install.installed = true
        //把Vue构造函数定义到全局变量
        _Vue = Vue
        // 把创建vue实例时传入的router对象注入到vue实例上
        _Vue.mixin({
            beforeCreate(){
                if(this.$options.router){
                    _Vue.prototype.$router = this.$options.router
                    this.$options.router.init()
                }
            }
        })
    }
    constructor(options){
        this.options = options
        this.routerMap = {}
        this.data = _Vue.observable({
            current: '/'
        })
    }
    init(){
        this.createRouterMap()
        this.initComponents(_Vue)
        this.initEvent()
    }
    createRouterMap(){
        this.options.routes.forEach(router => {
            this.routerMap[router.path] = router.component
        });
    }
    initComponents(Vue){
        const self = this
        Vue.component('router-link', {
            props: {
                to: String
            },
            render(h){
                return h('a',{
                    attrs: {
                        href: this.to
                    },
                    on:{
                        click:this.clickHandle
                    },
                },[this.$slots.default])
            },
            methods:{
                clickHandle(e){
                    if(self.options.mode === 'history'){
                        history.pushState({},'',this.to)
                    }else {
                        location.hash = this.to
                    }
                    
                    this.$router.data.current = this.to
                    e.preventDefault()
                }
            }
            // template: '<a :href="to"><slot></slot></a>' //运行时app没有模板编译
        })
        Vue.component('router-view',{
            render(h){
                const component = self.routerMap[self.data.current]
                return h(component)
            }
        })
    }
    initEvent(){
        if(this.options.mode === 'history'){
            let pathname = window.location.pathname
            this.data.current = pathname
            window.addEventListener('popstate', ()=>{
                this.data.current = window.location.pathname
            })
        }else {
            let hashname = window.location.hash
            this.data.current = hashname
            window.addEventListener("hashchange", () => {
                this.data.current = window.location.hash
            }, false);
        }
    }
}
